package com.g8.pethospitallearnbackend.interceptors;

import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.utils.JWTUtil;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component //注册拦截器 将其放入ioc容器中
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AuthRequird authReqOnContro = handlerMethod.getBean().getClass().getDeclaredAnnotation(AuthRequird.class);
        AuthRequird authReOnMeth = handlerMethod.getMethod().getDeclaredAnnotation(AuthRequird.class);

        // 如果不用权限控制，就直接过
        if (authReqOnContro == null && authReOnMeth == null) return true;
        if (authReOnMeth != null && !authReOnMeth.required()) return true;
        if (authReqOnContro != null && !authReqOnContro.required() && authReOnMeth == null) return true;

        Map<String, Object> map = new HashMap<>();
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        log.info("请求头中的token是:{}",token);
        map.put("code",0);
        try {
            // 这里返回的角色和注解中要求的角色一样，那么就需要权限控制
            int role = JWTUtil.getRole(token);
            if (authReOnMeth != null && role == authReOnMeth.role().getCode()) return true;
            else if (authReOnMeth == null && role == authReqOnContro.role().getCode()) return true;
        } catch (Exception e) {
            map.put("msg",e.getMessage());
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "token无效！可能未登录"+e.getMessage());
        }
        throw new CustomException(ResponseStatusEnum.NO_ACCESS);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
